<template>
  <div class="echarts-card-container">
    <h4 :style="{ marginBottom: '0' }" v-if="fullScreenShow">{{ title }}</h4>
    <a-icon type="fullscreen" v-if="isShow && fullScreenShow" @click="getFullScreen"></a-icon>
    <div :id="uuid" v-if="isShow" class="echarts-container"></div>
    <a-empty v-if="!isShow" description="暂无数据" />
  </div>
</template>

<script>
export default{
  name: 'EchartsCard',
  props: {
    option: {
      type: Object,
      default: () => {
        return {}
      }
    },
    title: {
      type: String,
      default: ''
    },
    fullScreenShow: {
      type: Boolean,
      default: true
    },
    height: {
      type: Number,
      default: 300
    },
    svg: {
      type: Boolean,
      default: true
    }
  },
  data(){
    return{
      uuid: '',
      dom: '',
      myChartList: []
    }
  },
  computed: {
    isShow(){
      return this.option && Object.keys(this.option) && Object.keys(this.option).length;
    }
  },
  created(){
    this.uuid = window.performance.now()
  },
  inject: ["getFullScreenProvide"],
  mounted(){
    let myChart;
    let dom = document.getElementById(this.uuid)
    if(!dom) return;
    let initStyle = () => {
      dom.style.width = dom.parentNode.clientWidth + 'px'
      dom.style.height = `${this.height}px`
    }
    this.$nextTick(() => {
      setTimeout(() => {
        initStyle()
        if(this.svg){
          //将canvas转换成svg, 解决canvas缩放失真
          myChart = this.$echarts.init(dom, null, { renderer : 'svg' })
        }else{
          //dialog中svg格式会出现错乱文字
          myChart = this.$echarts.init(dom)
        }
        myChart.setOption(this.option)
        this.myChartList.push(myChart)
      }, 0)
    })
    window.addEventListener('resize', () => {
      if(myChart){
        myChart.dispose()
        myChart = null;
      }
    })
  },
  beforeDestroy(){
    window.removeEventListener('resize', () => {})
    this.myChartList.forEach(item => {
      item.dispose()
      item = null;
    })
  },
  methods: {
    getFullScreen(){
      this.getFullScreenProvide(this.title, this.option)
    }
  }
}
</script>
<style lang="less" scoped>
h4{
  text-align: center;
  font-size: 16px;
  font-weight: 700;
}
.ant-empty{
  height: 300px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
</style>